A lot of the Google Maps geographic functionality can be got at programmatically! This can be really useful for getting information about a place, even when you don't want to show it on a map.
Here we will look at the 'Google Places' web API, and along the way we'll learn how to use web service APIs in general. We saw a little bit of this with text collation, so this time we'll look a little more carefully at how the web part works.
The first thing we will need is a Python library for talking to the Web. The best one out there at the moment is the 'requests' library, which doesn't come standard in Python but which you probably already have installed. If this doesn't work, go to a command / terminal window and type
pip install requests
or
pip3 install requests
if you are on a Mac.
In [1]:
import requests
You have some place name, and you want to find out where it is. We do this using two API functions provided by Google, first to get the ID of the place, and then to get more information about it.
Google, like Zotero, requires an API key to use its web API. This is because Google sets limits to how much you can use it for free. The limits should plenty for a normal person's use, though.
For the time being, you can use the API key that I have put in ILIAS. If you are going to do your own work with Maps, though, then you should go to http://developers.google.com/ and sign up as a developer. You'll then need to create a project, and in that project go to 'API keys & auth' -> and set up access for the API you want to use. The one we're using today is the Google Places API Web Service. You'll then need to go to 'Credentials' to make your API key. If you need further help with the options, then talk to me!
Google's documentation for the Places API is here: https://developers.google.com/places/webservice/intro
and today we'll be using the Place Search and Place Details functions.
In [2]:
search_endpoint = 'https://maps.googleapis.com/maps/api/place/textsearch/json'
search_params = {
'query': 'Länggass Stübli',
'key': 'AIzaSyCNx-klDCfhopV6W_QPFZ0iwv5sp1J0XwQ',
'language': 'en'
}
r = requests.get( search_endpoint, params=search_params)
r.json() # See what we got
Out[2]:
Once we have successfully looked up a place, we will have an ID for it. This is Google's way of distinguishing between places of the same name, so that we know we have the right one. We can use that ID to get information about a place we have already looked up with the details API function.
In [3]:
search_result = r.json()
details_endpoint = 'https://maps.googleapis.com/maps/api/place/details/json'
dparams = {
'key': 'AIzaSyCNx-klDCfhopV6W_QPFZ0iwv5sp1J0XwQ',
'placeid': search_result['results'][0]['place_id'],
'language': 'en'
}
r = requests.get( details_endpoint, params=dparams)
r.json() # See what we got
Out[3]:
Now let's look up a series of places! We'll store our results in places_found, for each place that we find.
In [4]:
places_to_lookup = ['Moskva', 'Venice', 'Rosslyn Chapel', 'Cantabrigia']
places_found = {}
for p in places_to_lookup:
myparams = {
'query': p,
'key': 'AIzaSyCNx-klDCfhopV6W_QPFZ0iwv5sp1J0XwQ',
'language': 'en'
}
myr = requests.get( search_endpoint, params=myparams )
myresult = myr.json()
if 'results' in myresult and len(myresult['results']) > 0:
print("Found information for %s" % p)
places_found[p] = myresult['results'][0]
In [5]:
places_found
Out[5]:
One thing we can do with the Places API is to look up a bunch of places, get their latitude and longitude or their canonical names, and put those into a big spreadsheet for use elsewhere (or even for importing into Google Maps to make a map!)
The easiest way to make something like a spreadsheet in a computer program is to use CSV, which stands for comma separated values. That is what we used earlier to get our UK fat supply data into our map. Python has a built-in module for this, and we use it like this to make a CSV file.
In [6]:
import csv
f = open('myplaces.csv', 'w', newline='', encoding='utf-8')
writer = csv.writer(f)
# First, write our column headers!
writer.writerow(['Place name', 'Address', 'ID', 'Latitude', 'Longitude'])
Out[6]:
Now we have an open file called 'myplaces.csv', and we have written one row to it. If you were to close the filehandle now and look at the file, you would see that it looks like this:
Place name,Address,ID,Latitude,Longitude
But we won't close the file yet, because we want to write each of our places into its row.
In [7]:
for p in places_found.keys():
place_info = places_found[p]
address = place_info['formatted_address']
placeid = place_info['place_id']
latitude = place_info['geometry']['location']['lat']
longitude = place_info['geometry']['location']['lng']
writer.writerow([p, address, placeid, latitude, longitude])
f.close() # Always close what you open, if you didn't use 'with'!
Now we can make sure the file is there and has what we expect!
In [8]:
with open('myplaces.csv', encoding='utf-8') as f:
data = f.read()
print(data)
And now it is ready for processing anywhere you like, including putting back into Google Maps if you so choose.